package indi.madoka.weeb.module.base.service;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

/**
 * @author Arcueid
 */
@Service
@Slf4j
public class SetuService {
    private final WebClient webClient;
    private static final String LOLICON_API_URL = "https://api.lolicon.app/setu/v2";

    public SetuService(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.baseUrl(LOLICON_API_URL).build();
    }

    public String getRandomPicture(){
        Mono<String> apiRequest = loliconApiRequest();
        return getResultImageUrl(apiRequest.block());
    }

    public String getTaggedPicture(String tag){
        Mono<String> apiRequest = loliconApiRequest(Param.TAG,tag);
        return getResultImageUrl(apiRequest.block());
    }

    public String getUidPicture(String uid){
        Mono<String> apiRequest = loliconApiRequest(Param.UID, uid);
        return getResultImageUrl(apiRequest.block());
    }

    private Mono<String> loliconApiRequest() {
        return this.webClient.get()
                .retrieve()
                .bodyToMono(String.class);
    }

    private Mono<String> loliconApiRequest(Param param, String value){
        return this.webClient.get()
                .uri(String.format("?%s=", param.toString().toLowerCase()) + value)
                .retrieve()
                .bodyToMono(String.class);
    }

    private String getResultImageUrl(String result) {
        JSONObject resultInJson = parseResultToJson(result);
        try {
            return resultInJson.getJSONArray("data")
                    .getJSONObject(0)
                    .getJSONObject("urls")
                    .getString("original");
        }catch (Exception e){
            return null;
        }
    }

    private JSONObject parseResultToJson(String result){
        return JSONObject.parseObject(result);
    }

    enum Param{
        /**
         * UID
         */
        UID,
        /**
         * tag
         */
        TAG
    }
}
